﻿using BPMN.Application.Contracts.DTO.Defective;
using BPMN.Application.Contracts.DTO.Request.UserInfo;
using BPMN.Application.Contracts.DTO.Response;
using BPMN.Application.Contracts.DTO.Response.UserInfo;
using BPMN.Application.IService;
using BPMN.Domain.Entity.DefectiveModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration.UserSecrets;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace BPMN.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class IDefectiveController : ControllerBase
    {

        public IDefectiveController(IDefectiveService defective)
        {
            Defective = defective;
        }

        public IDefectiveService Defective { get; }



        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="defective"></param>
        /// <returns></returns>
        [HttpPost("AddDefective")]
        public async Task<IActionResult> AddDefective(Defective defective)
        {
            return Ok(await Defective.AddDefective(defective));

        }



        //获取不良品相所有数据
        [HttpGet("responseDto")]
        public async Task<IActionResult> responseDto(string BianHoa, string DefName)
        {
            return Ok(await Defective.responseDto(BianHoa, DefName));

        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        public IActionResult UploadFile(IFormFile file)
        {
            try
            {
                string path = Directory.GetCurrentDirectory() + "//wwwroot//PIc/" + file.FileName;

                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Close();
                }
                return Ok(file.FileName);

            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut("DeleteDefective")]
        public async Task<IActionResult> DeleteDefective(List<int> ids)
        {
            return Ok(await Defective.DeleteDefective(ids));

        }


        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("DefectiveFanTian")]
        public async Task<IActionResult> DefectiveFanTian(int id)
        {
            return Ok(await Defective.DefectiveFanTian(id));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="defective"></param>
        /// <returns></returns>
        [HttpPut("UpdDefective")]
        public async Task<IActionResult> UpdDefective(Defective defective)
        {
            return Ok(await Defective.UpdDefective(defective));
        }

        [HttpGet("DaoChu")]
        public async Task<IActionResult> DaoChu()
        {
            var stdList = (await Defective.responseDto("","")).Data;
            ExcelHelper<DefectiveDto>.SaveExcelFile("D:\\新建文件夹\\桌面\\项目1\\不良品相表.xls", "Defective", stdList);

            return Ok("导出成功");

        }

        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        [HttpPost("UploadUserInfo")]
        public async Task<IActionResult> UploadUserInfo(IFormFile excelFile)
        {
            try
            {
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(new
                    {
                        error = 1,
                        msg = "必须是Excel文件"
                    });
                }

                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }
                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;

                List<Defective> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);
                    // 判定第5列的值是不是日期，日期的值类型可以按日期来读，也可以用数据的方式来读
                    //var isDate = DateUtil.IsCellDateFormatted(row.GetCell(4));

                    string UserName = row.GetCell(1).StringCellValue;
                    string Name = row.GetCell(2).StringCellValue;
                    string Tel = row.GetCell(3).StringCellValue;
                    string Email = row.GetCell(4).StringCellValue;

                

                    var stu = new Defective
                    {
                         Defective_BianHao = UserName,
                        Defective_Name = Name,
                        Defective_attachments = Tel,
                        Defective_Img = Email,
                         
                    };
                    stuList.Add(stu);
                }
                foreach (var item in stuList)
                {
                    await Defective.AddDefective(item);

                }
                wb.Close();
                return Ok(1);
            }
            catch (Exception)
            {
                throw;
            }
        }











    }






}


